const express = require('express');
const { Op } = require('sequelize');
const router = express.Router();
const { courseFilterBody } = require('../../utils/filter-req');
const { success, failure } = require('../../utils/responses');
const { NotFound, Conflict } = require('http-errors');
const { Course, Category, User, Chapter } = require('../../models');


function getCondition() {
  return {
    /**排除大写 分类id和用户id */
    attributes: { exclude: ['CategoryId', 'UserId'] },
    include: [
      {
        model: Category,
        as: 'category', //将查出的分类和用户大写改小写别名
        attributes: ['id', 'name'],
      },
      {
        model: User,
        as: 'user', //将查出的分类和用户大写改小写别名
        attributes: ['id', 'username', 'avatar'],
      },
    ],
  };
}
const getList = async (req) => {
  const { id } = req.params;
  const course = await Course.findByPk(id, getCondition());
  if (!course) {
    throw new NotFound(`ID：${id}不存在`);
  }
  return course;
};
router.get('/', async (req, res) => {
  try {
    let { categoryId, userId, name, recommended, introductory, currentPage, pageSize } = req.query;
    pageSize = Math.abs(Number(pageSize || 10));
    currentPage = Math.abs(Number(currentPage || 1));
    const condition = {
      order: [['id', 'DESC']],
      ...getCondition(),
      limit: pageSize,
      offset: (currentPage - 1) * pageSize,
      where: {},
    };

    if (categoryId) {
      condition.where.categoryId = {
        [Op.eq]: categoryId,
      };
    }

    if (userId) {
      condition.where.userId = {
        [Op.eq]: userId,
      };
    }

    if (name) {
      condition.where.name = {
        [Op.like]: `%${name}%`,
      };
    }

    if (recommended) {
      condition.where.recommended = {
        // 需要转布尔值
        [Op.eq]: recommended === 'true',
      };
    }

    if (introductory) {
      condition.where.introductory = {
        [Op.eq]: introductory === 'true',
      };
    }

    const { count, rows } = await Course.findAndCountAll(condition);

    const data = {
      data: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    };
    success({
      res,
      data,
    });
  } catch (error) {
    // 返回错误信息
    failure({ res, error });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const course = await getList(req);
    success({ res, data: course });
  } catch (error) {
    failure({ res, error });
  }
});
router.post('/', async (req, res) => {
  try {
    //用挂载在req的用户id
    req.body.userId = req.user.id;

    const body = courseFilterBody(req.body);
    const course = await Course.create(body);

    //200状态么和201不同， 201表示请求成功并且创建新的资源 更专业
    success({ res, code: 201, message: '创建成功' });

  } catch (error) {
    failure({ res, error, message: '创建失败' });
  }
});
router.delete('/:id', async (req, res) => {
  try {
    const course = await getList(req);

    const count = await Chapter.count({ where: { courseId: req.params.id } });

    if (count > 0) {
      throw Conflict('当前课程有关联章节，无法删除');
    }
    //删除
    await course.destroy();

    success({ res, message: '删除成功' });
  } catch (error) {
    failure({ res, error, message: '删除失败' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const course = await getList(req);
    const body = courseFilterBody(req.body);
    await course.update(body);

    success({ res, message: '更新成功' });
  } catch (error) {
    failure({ res, error });
  }
});





module.exports = router;
